import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import 'package:sports_new/entity/ai/chart_match_entity.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/resources/styles.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/view/pick/ai/ai_type.dart';
import 'package:sports_new/view/pick/items/chart_info_row.dart';
import 'package:sports_new/view/pick/items/chart_match_info.dart';
import 'package:sports_new/view/pick/items/chart_notice.dart';
import 'package:sports_new/widgets/card.dart';
import 'package:sports_new/widgets/loading/loading_widget.dart';
import '../../../entity/ai/chart_radar_entity.dart';
import '../../../server/api/ai_api.dart';
import '../../../widgets/base/qkd_text.dart';

class ChartRadarPage extends StatefulWidget {
  const ChartRadarPage({super.key, required this.type, required this.matchId});

  final AiType type;
  final int matchId;

  @override
  State<ChartRadarPage> createState() => _ChartRadarPageState();
}

class _ChartRadarPageState extends State<ChartRadarPage> {
  final Color borderColor = const Color(0xFFEFEFEF);
  ChartRadarEntity? entity;
  List<String> optionName = [];
  List<String> option = [];
  String point = "";
  Offset? position;
  Map<String, double>? rateRange;

  @override
  void initState() {
    getData();
    super.initState();
  }

  Future getData() async {
    ChartRadarEntity? data =
        await AiApi.getRadar(widget.matchId, widget.type.tag);
    setState(() {
      entity = data;
      optionName = [
        if (entity?.aiIndexName.hasValue == true) entity!.aiIndexName!,
        if (entity?.option != null) "选项建议"
      ];
      option = [
        if (entity?.aiIndex.hasValue == true) entity!.aiIndex!,
        if (entity?.option != null) entity!.option!
      ];
      rateRange = {
        "min": entity?.radarData
                ?.map<double?>((e) => e.rate)
                .toList()
                .min()
                ?.toDouble() ??
            0,
        "max": entity?.radarData
                ?.map<double?>((e) => e.rate)
                .toList()
                .max()
                ?.toDouble() ??
            0,
      };
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colours.greyF2F3F7,
      appBar: Styles.appBar(
          titleSpacing: 0,
          titleTextStyle: const TextStyle(fontSize: 14, color: Colours.text),
          title: QkdText(widget.type.name ?? "",
              fontWeight: FontWeight.w500, fontSize: 18)),
      body: LoadingWidget<int>(
        isLoading: entity == null,
        data: 1,
        child: () => SingleChildScrollView(
          child: Column(
            children: [
              Block(
                  cardStyle: const CardStyle(
                    margin: EdgeInsets.fromLTRB(12, 12, 12, 0),
                  ),
                  child: Column(
                    children: [
                      Container(height: 12),
                      ChartMatchInfo(
                          info: ChartMatchEntity.fromJson(entity!.toJson())),
                      Container(height: 20),
                      ChartInfoRow(
                        indexName: entity?.aiIndexName ?? "",
                        index: entity?.aiIndex ?? "",
                        level: entity?.level,
                        advice: entity?.option ?? "",
                        maxNum: widget.type == AiType.lm ? 5 : 10,
                      )
                    ],
                  )),
              Block(
                cardStyle: const CardStyle(
                    margin: EdgeInsets.all(12), padding: EdgeInsets.all(16)),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    QkdText("${widget.type == AiType.lm ? "冷门" : "定胆"}雷达图",
                        fontSize: 16, fontWeight: FontWeight.w500),
                    Container(height: 12),
                    Transform.scale(
                      scale: 0.85,
                      child: AspectRatio(
                        aspectRatio: 1,
                        child: RadarChart(
                          RadarChartData(
                            dataSets: [
                              RadarDataSet(
                                  dataEntries: List.generate(
                                      entity?.radarData?.length ?? 0,
                                      (index) => RadarEntry(
                                          value:
                                              (entity?.radarData?[index].rate ??
                                                      0) *
                                                  100.0.toInt())),
                                  fillColor:
                                      const Color(0xFFF65252).withOpacity(0.1),
                                  borderColor: const Color(0xFFF65252),
                                  borderWidth: 1,
                                  entryRadius: 4)
                            ],
                            getTitle: (index, angle) => RadarChartTitle(
                                text:
                                    "${entity?.radarData?[index].name}\n${((entity?.radarData?[index].rate ?? 0) * 100).toInt()}%",
                                angle: 0,
                                positionPercentageOffset: 0.12),
                            radarTouchData: RadarTouchData(
                                enabled: true,
                                touchCallback: (event, response) {
                                  // position = event.localPosition;
                                  position = response?.touchedSpot?.offset;
                                  point = response
                                          ?.touchedSpot?.touchedRadarEntry.value
                                          .toString() ??
                                      "";
                                  if (!event.isInterestedForInteractions)
                                    point = "";
                                  setState(() {});
                                }),
                            tickCount: 5,
                            radarShape: RadarShape.polygon,
                            titleTextStyle: const TextStyle(
                                fontSize: 13, color: Colours.grey66),
                            ticksTextStyle: const TextStyle(
                                fontSize: 11, color: Colours.transparent),
                            tickBorderData: BorderSide(color: borderColor),
                            gridBorderData: BorderSide(color: borderColor),
                            radarBorderData: BorderSide(color: borderColor),
                          ),
                        ),
                      ),
                    ),
                    ChartNotice(tips: entity?.tips ?? []),
                  ],
                ),
              ),
              Container(height: 50)
            ],
          ),
        ),
      ),
    );
  }
}
